package main

import(
	"log"
	"encoding/json"
	"crypto/tls"
	"net/http"
	"io/ioutil"
	"regexp"
	"strings"
)

type Req struct{
	C chan string
}

func (this *Req) start(){
	go this.url()
	for{
		select{
		case msg := <- this.C:
			log.Println(msg)
		}
	}
}

func (this *Req) url(){
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify:true,
		},
	}
	clinet := &http.Client{Transport: tr}
	resp, err := clinet.Get("https://image.baidu.com/wisehomepage/feeds/atlas?word=%E4%BA%8C%E6%AC%A1%E5%85%83&reqfdi=0&fmpage=result&pos=pstab&uistyle=2&pn=0&rn=10&index=1")
	if err != nil {
        log.Panicln("error:", err)
        return
    }
    defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	bodyStr := string(body)
	//log.Println(bodyStr)
	exp2 := regexp.MustCompile(`Atlas\.init\(([\s\S\n]*?)\)`)
	result2 := exp2.FindAllStringSubmatch(bodyStr, -1)
	//log.Println(result2)
	//log.Println(result2[0][1])
	if len(result2) > 0 && len(result2[0]) > 0{
		s := result2[0][1]
		s = strings.Replace(s, "\n", "", -1)
		s = strings.Replace(s, " ", "", -1)
		s = strings.Replace(s, "'", "\"", -1)
		//log.Println("=====================", s)
		exp2 = regexp.MustCompile(`\[([\s\S]*)\]`)
    	result3 := exp2.FindAllStringSubmatch(s, -1)
    	ioutil.WriteFile("test.txt", []byte(result3[0][0]), 0644)
		//log.Println("=====================", result3)
		var data []map[string]interface{}
		if err := json.Unmarshal([]byte(result3[0][0]), &data); err != nil {
			log.Panicln(err.Error())
    	}
    	log.Println(data)

	}
}